/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2009 Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Sam Lantinga
    slouken@libsdl.org
*/

#include "../SDL_cellvideo.h"
#include "SDL_mouse.h"
#include "../../../events/SDL_events_c.h"
#include <cell/mouse.h>

/* Data */
#define PS3_MAX_MOUSE_BUTTONS 3
static const uint32_t			ButtonMapping[PS3_MAX_MOUSE_BUTTONS] = {1, 3, 2}; //Map CELL buttons to SDL buttons

/* Helpers */
static void						CheckMouse							()
{
	if(60 < CELL_Video.Mouse.Check ++)
	{
		CellMouseInfo MouseInfo;
		cellMouseGetInfo(&MouseInfo);

		if(!CELL_Video.Mouse.Have && (MouseInfo.status[0] == CELL_MOUSE_STATUS_CONNECTED))
		{
			CELL_Video.Mouse.Have = 1;
			CELL_Video.Mouse.Buttons = 0;

			cellMouseClearBuf(0);
		}
		else if(CELL_Video.Mouse.Have && MouseInfo.status[0] != CELL_MOUSE_STATUS_CONNECTED)
		{
			CELL_Video.Mouse.Have = 0;
			CELL_ReleaseAllMouseButtons();
		}

		CELL_Video.Mouse.Check = 0;
	}
}

static void						ProcessButtons					(uint32_t aOldButtons, uint32_t aNewButtons)
{
	if(aNewButtons != aOldButtons)
	{
		for(int i = 0; i != PS3_MAX_MOUSE_BUTTONS; i ++)
		{
			if((aOldButtons & (1 << i)) != (aNewButtons & (1 << i)))
			{
				CELL_DoMouseEvent(ButtonMapping[i], (aNewButtons & (1 << i)) ? SDL_PRESSED : SDL_RELEASED);
			}
		}
	}
}

/* Implementation */
void							CELL_MOUSE_Process				()
{
	CheckMouse();

	if(CELL_Video.Mouse.Have)
	{
		CellMouseDataList data;

		do
		{
			cellMouseGetDataList(0, &data);

			for(int i = 0; i != data.list_num; i ++)
			{
				if(data.list[i].update != CELL_MOUSE_DATA_NON)
				{
					if(CELL_Video.Mouse.Buttons != data.list[i].buttons)
					{
						ProcessButtons(CELL_Video.Mouse.Buttons, data.list[i].buttons);
						CELL_Video.Mouse.Buttons = data.list[i].buttons;
					}

					if(data.list[i].x_axis || data.list[i].y_axis)
					{
						SDL_PrivateMouseMotion(0, 1, data.list[i].x_axis, data.list[i].y_axis);
					}
				}
			}
		}	while(data.list_num);
	}
}

